#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIOT智能学习桌项目 - 语音识别依赖安装脚本
自动安装SpeechRecognition、pyaudio、pyttsx3等依赖包
"""

import subprocess
import sys
import os
import platform

def print_banner():
    """打印安装横幅"""
    print("="*60)
    print("🎤 AIOT智能学习桌 - 语音识别依赖安装")
    print("="*60)
    print("📦 将要安装的包:")
    print("   - SpeechRecognition (语音识别)")
    print("   - pyaudio (音频处理)")
    print("   - pyttsx3 (语音合成)")
    print("="*60)

def check_system():
    """检查系统环境"""
    print("\n🔍 检查系统环境...")
    
    # 检查Python版本
    python_version = sys.version_info
    print(f"🐍 Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    if python_version.major < 3 or (python_version.major == 3 and python_version.minor < 6):
        print("❌ Python版本过低，建议使用Python 3.6+")
        return False
    
    # 检查操作系统
    system = platform.system()
    print(f"💻 操作系统: {system}")
    
    # 检查pip
    try:
        subprocess.run([sys.executable, "-m", "pip", "--version"], 
                      capture_output=True, check=True)
        print("✅ pip 可用")
    except subprocess.CalledProcessError:
        print("❌ pip 不可用")
        return False
    
    return True

def install_package(package_name, description=""):
    """安装单个包"""
    print(f"\n📦 正在安装 {package_name}...")
    if description:
        print(f"   功能: {description}")
    
    try:
        # 升级pip
        subprocess.run([
            sys.executable, "-m", "pip", "install", "--upgrade", "pip"
        ], capture_output=True)
        
        # 安装包
        result = subprocess.run([
            sys.executable, "-m", "pip", "install", package_name
        ], capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"✅ {package_name} 安装成功")
            return True
        else:
            print(f"❌ {package_name} 安装失败")
            print(f"错误信息: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ 安装 {package_name} 时出错: {e}")
        return False

def install_pyaudio_windows():
    """在Windows上安装pyaudio"""
    print("\n🔧 Windows系统特殊处理 pyaudio...")
    
    # 尝试使用预编译的wheel
    try:
        import platform
        python_version = f"{sys.version_info.major}{sys.version_info.minor}"
        architecture = "win_amd64" if platform.machine().endswith('64') else "win32"
        
        print(f"🎯 检测到 Python {python_version} {architecture}")
        
        # 尝试直接安装
        result = subprocess.run([
            sys.executable, "-m", "pip", "install", "pyaudio"
        ], capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✅ pyaudio 安装成功")
            return True
        else:
            print("⚠️ 直接安装失败，尝试其他方法...")
            
            # 提示用户手动安装
            print("\n💡 如果pyaudio安装失败，请尝试以下方法:")
            print("1. 安装Visual Studio Build Tools")
            print("2. 或者从以下网站下载预编译的wheel:")
            print("   https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio")
            print("3. 然后使用: pip install 下载的.whl文件")
            
            return False
            
    except Exception as e:
        print(f"❌ pyaudio安装出错: {e}")
        return False

def verify_installation():
    """验证安装结果"""
    print("\n🔍 验证安装结果...")
    
    packages = [
        ("speech_recognition", "SpeechRecognition"),
        ("pyaudio", "pyaudio"),
        ("pyttsx3", "pyttsx3")
    ]
    
    success_count = 0
    
    for import_name, package_name in packages:
        try:
            __import__(import_name)
            print(f"✅ {package_name} 验证通过")
            success_count += 1
        except ImportError:
            print(f"❌ {package_name} 验证失败")
    
    return success_count == len(packages)

def test_microphone():
    """测试麦克风功能"""
    print("\n🎤 测试麦克风功能...")
    
    try:
        import speech_recognition as sr
        
        # 列出可用麦克风
        print("🔍 可用麦克风设备:")
        microphones = sr.Microphone.list_microphone_names()
        
        if not microphones:
            print("❌ 未检测到麦克风设备")
            return False
        
        for i, mic_name in enumerate(microphones):
            print(f"   {i}: {mic_name}")
        
        # 测试默认麦克风
        recognizer = sr.Recognizer()
        microphone = sr.Microphone()
        
        print("\n🔧 调整麦克风设置...")
        with microphone as source:
            recognizer.adjust_for_ambient_noise(source, duration=1)
            print(f"✅ 麦克风调整完成，噪音阈值: {recognizer.energy_threshold}")
        
        return True
        
    except Exception as e:
        print(f"❌ 麦克风测试失败: {e}")
        return False

def test_tts():
    """测试语音合成功能"""
    print("\n🔊 测试语音合成功能...")
    
    try:
        import pyttsx3
        
        engine = pyttsx3.init()
        
        # 获取语音属性
        voices = engine.getProperty('voices')
        print(f"🗣️ 可用语音: {len(voices)}个")
        
        # 设置语音属性
        engine.setProperty('rate', 150)
        engine.setProperty('volume', 0.8)
        
        # 测试语音播报
        test_text = "语音合成测试成功"
        print(f"🔊 播报测试: {test_text}")
        
        engine.say(test_text)
        engine.runAndWait()
        
        print("✅ 语音合成测试通过")
        return True
        
    except Exception as e:
        print(f"❌ 语音合成测试失败: {e}")
        return False

def main():
    """主安装函数"""
    print_banner()
    
    # 检查系统环境
    if not check_system():
        print("\n❌ 系统环境检查失败，请解决后重试")
        return
    
    # 询问用户是否继续
    confirm = input("\n是否继续安装？(y/n): ").strip().lower()
    if confirm != 'y':
        print("🛑 用户取消安装")
        return
    
    print("\n🚀 开始安装语音识别依赖...")
    
    # 安装包列表
    packages = [
        ("SpeechRecognition", "语音识别库"),
        ("pyttsx3", "语音合成库")
    ]
    
    success_count = 0
    
    # 安装基础包
    for package, description in packages:
        if install_package(package, description):
            success_count += 1
    
    # 特殊处理pyaudio
    if platform.system() == "Windows":
        if install_pyaudio_windows():
            success_count += 1
    else:
        if install_package("pyaudio", "音频处理库"):
            success_count += 1
    
    # 验证安装
    print("\n" + "="*60)
    if verify_installation():
        print("🎉 所有依赖安装成功！")
        
        # 测试功能
        print("\n🧪 功能测试:")
        test_microphone()
        test_tts()
        
        print("\n✅ 语音识别环境配置完成")
        print("💡 现在可以运行语音识别功能了")
        
    else:
        print("⚠️ 部分依赖安装失败")
        print("💡 请检查错误信息并手动安装")
    
    print("\n" + "="*60)
    print("📚 使用说明:")
    print("1. 运行 启动菜单.py")
    print("2. 选择 '2. 语音识别集成版本'")
    print("3. 或选择 '3. 语音识别模块测试'")
    print("="*60)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n🛑 安装被用户中断")
    except Exception as e:
        print(f"\n❌ 安装过程出错: {e}")
        print("💡 请检查系统环境和网络连接")
    
    input("\n按 Enter 键退出...") 